package com.tjnu.losca.core;

import com.tjnu.losca.pojo.Img;
import com.tjnu.losca.service.IImgService;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import io.minio.errors.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author Losca
 * @date 2021/9/23 21:58
 */
@Component
public class FileUtil {

    @Autowired
    private IImgService imgService;

    @Value("${file.minio.url}")
    private String minioUrl;
    @Value("${file.minio.username}")
    private String minioUsername;
    @Value("${file.minio.password}")
    private String minioPassword;
    @Value("${file.minio.img}")
    private String img;

    public String imgUpload(MultipartFile file) throws InvalidPortException, InvalidEndpointException, IOException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        //没有上传头像默认为2.jpg
        if (file == null || file.getSize() == 0){
            return img;
        }
        //解析文件的md5
        String md5Hex = DigestUtils.md5Hex(file.getInputStream());
        //获取文件大小
        long size = file.getSize();
        //获取文件后缀名
        String suffix = FilenameUtils.getExtension(file.getOriginalFilename());
        //通过md5 size suffix判断文件是否上传过
        Img img = imgService.getOne(md5Hex, size, suffix);
        if (img != null){
            return img.getPath();
        }
        MinioClient minioClient = new MinioClient(minioUrl, minioUsername, minioPassword);
        PutObjectOptions options = new PutObjectOptions(size,0);
        //设置文件格式，图片能够被在线预览
        options.setContentType(file.getContentType());
        StringBuilder builder = new StringBuilder();
        //生成文件名 时间戳+随机数
        builder.append(System.currentTimeMillis()+RandomStringUtils.random(6,false,true));
        //生成文件名后缀
        builder.append(".").append(suffix);
        // 使用putObject上传一个文件到存储桶中。
        minioClient.putObject("img",builder.toString(),file.getInputStream(),options);
        //把img信息存储到数据库
        img = new Img(md5Hex,size,suffix,builder.toString());
        imgService.save(img);
        return builder.toString();
    }

}
